<template>
  <div id="user-wrap">
    <div class="add-user">
      <el-button icon="iconfont icon-jiufuqianbaoicon06" size="mini" class="exportBtn add" @click="addUser('添加')"
        >添加用户</el-button
      >
    </div>
    <div class="list-container">
      <div class="tables">
        <el-table
          :data="tableData"
          class="table"
          height="100%"
          ref="jdjgTable"
          @sort-change="sortChange"
          :header-cell-style="{
            padding: '0px',
            background: 'linear-gradient(0deg, #F4F6F9, #EAECF4, #F3F6F9)'
          }"
          :row-class-name="tabRowClassName"
          header-row-class-name="mapTable_th"
        >
          <el-table-column width="60" align="center" type="index" :index="addIndex" label="序号">
            <el-table-column width="60" align="center" type="index" label="检索"> </el-table-column>
          </el-table-column>
          <el-table-column label="姓名" align="center" width="150">
            <el-table-column width="150" align="center" sortable="custom" prop="userName">
              <template slot="header" align="center" slot-scope="{}">
                <div class="searchBox" @click.stop>
                  <el-input v-model.trim="searchPositionName" @change="getDataChange()"></el-input>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="手机" align="center" width="150">
            <el-table-column width="150" align="center" sortable="custom" prop="phone">
              <template slot="header" align="center" slot-scope="{}">
                <div class="searchBox" @click.stop>
                  <el-input v-model.trim="searchPositionName" @change="getDataChange()"></el-input>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="角色" align="center" width="150">
            <el-table-column width="150" align="center" sortable="custom" prop="role">
              <template slot="header" align="center" slot-scope="{}">
                <div class="searchBox" @click.stop>
                  <el-input v-model.trim="searchPositionName" @change="getDataChange()"></el-input>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="账号" align="center" width="150">
            <el-table-column width="150" align="center" sortable="custom" prop="loginName">
              <template slot="header" align="center" slot-scope="{}">
                <div class="searchBox" @click.stop>
                  <el-input v-model.trim="searchPositionName" @change="getDataChange()"></el-input>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="创建时间" align="center" width="180">
            <el-table-column width="180" align="center" sortable="custom" prop="createTime">
              <template slot="header" align="center" slot-scope="{}">
                <div class="searchBox" @click.stop>
                  <el-date-picker v-model.trim="value1" type="date" placeholder="选择日期"> </el-date-picker>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="状态" align="center" width="80">
            <el-table-column align="center" prop="type" width="80">
              <template slot-scope="scope">
                <div>
                  <span v-if="scope.row.type">正常</span>
                  <span v-else>停用</span>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="270">
            <el-table-column align="center" width="270">
              <template slot-scope="scope">
                <div class="">
                  <el-button type="text" class="xg czBtn" size="small" @click="handleClick('编辑', scope.row)">
                    编辑
                  </el-button>
                  <el-button type="text" class="ty czBtn" size="small" @click="handleClick('重置密码', scope.row)">
                    重置密码
                  </el-button>
                  <span
                    v-if="
                      scope.row.roleCode !== 'admin' &&
                      scope.row.roleCode !== 'pAdmin' &&
                      scope.row.roleCode !== 'mAdmin' &&
                      scope.row.roleCode !== 'youke'
                    "
                  >
                    <el-button
                      v-if="scope.row.type"
                      type="text"
                      class="ty czBtn"
                      size="small"
                      @click="handleClick('停用', scope.row)"
                    >
                      停用
                    </el-button>
                    <el-button v-else type="text" class="xg czBtn" size="small" @click="handleClick('启用', scope.row)">
                      启用
                    </el-button>
                  </span>
                  <el-button
                    type="text"
                    class="sc czBtn"
                    size="small"
                    v-if="
                      scope.row.roleCode !== 'admin' &&
                      scope.row.roleCode !== 'pAdmin' &&
                      scope.row.roleCode !== 'mAdmin' &&
                      scope.row.roleCode !== 'youke'
                    "
                    @click="handleClick('删除', scope.row)"
                  >
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </div>
      <element-pagination @getData="getPagChange" :Total="total"> </element-pagination>
    </div>
    <el-dialog
      width="432px"
      class="user-dialog"
      v-if="userVisible"
      :center="true"
      :close-on-click-modal="false"
      :title="title"
      :before-close="closeDialog"
      :visible.sync="userVisible"
    >
      <el-form ref="form" class="infoForm" label-width="70px">
        <el-form-item label="角色:" :required="true">
          <el-select
            :disabled="roleCode"
            ref="oneSelect"
            v-model.trim="roleId"
            placeholder="请添加角色"
            size="mini"
            @change="oneSelectChange"
          >
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名:" :required="true">
          <el-input v-model.trim="userName" clearable placeholder="请输入姓名" size="mini"> </el-input>
        </el-form-item>
        <el-form-item label="手机号:" :required="true">
          <el-input v-model.trim="userPhone" clearable placeholder="请输入手机号" size="mini"> </el-input>
        </el-form-item>
        <el-form-item label="账号:" :required="true">
          <el-input v-model.trim="userAccount" clearable placeholder="请输入账号" size="mini"> </el-input>
        </el-form-item>
      </el-form>
      <dialog-footer-button v-if="title === '添加用户'" @saveName="saveName('添加')" @close="close">
      </dialog-footer-button>
      <dialog-footer-button v-if="title === '修改用户'" @saveName="saveName('修改')" @close="close">
      </dialog-footer-button>
    </el-dialog>
  </div>
</template>

<script>
import ElementPagination from '../../../components/ElementPagination.vue'
import dialogFooterButton from '../../../components/dialogFooterButton.vue'
export default {
  components: { ElementPagination, dialogFooterButton },
  data() {
    return {
      title: '',
      roleId: null,
      roleIdCopy: null,
      roleCode: false,
      value1: [],
      tableData: [],
      searchPositionName: '',
      roleList: [],
      userId: null,
      userName: '',
      userPhone: '',
      userAccount: '',
      userVisible: false,
      total: 0,
      page: 1,
      size: 15
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    oneSelectChange() {},
    saveName(val) {
      if (this.userName && this.userPhone && this.userAccount && this.roleId) {
        if (val === '添加') {
          if (this.common.fieldTest('phone', this.userPhone)) {
            if (this.userName.length > 8) {
              this.$message.error('您输入的姓名太长，请重新输入小于八位的姓名')
              return false
            }
            this.$https({
              method: 'post',
              url: '/User/addUser',
              data: {
                loginName: this.userAccount,
                phone: this.userPhone,
                roleId: this.roleId,
                userName: this.userName
              }
            })
              .then(res => {
                if (res.code === 0) {
                  this.$message.success(res.msg)
                  this.close()
                  this.getData()
                } else {
                  this.$message.error(res.msg)
                }
              })
              .catch(err => {
                console.log(err)
              })
          } else {
            this.$message.error('请输入正确的手机号')
          }
        } else if (val === '修改') {
          if (this.common.fieldTest('phone', this.userPhone)) {
            // 如果是超管系列的修改
            if (this.roleCode) {
              this.roleId = this.roleIdCopy
            }
            this.$https({
              method: 'post',
              url: '/User/updateUser',
              data: {
                userId: this.userId,
                loginName: this.userAccount,
                phone: this.userPhone,
                roleId: this.roleId,
                userName: this.userName
              }
            })
              .then(res => {
                if (res.code === 0) {
                  this.$message.success(res.msg)
                  this.close()
                  this.getData()
                } else {
                  this.$message.error(res.msg)
                }
              })
              .catch(err => {
                console.log(err)
              })
          } else {
            this.$message.error('请输入正确的手机号')
          }
        }
      } else {
        this.$message.error('带*号的文本不能为空，请输入')
      }
    },
    async addUser(val, scope) {
      await this.getRoleList()
      if (val === '添加') {
        this.title = '添加用户'
      } else {
        this.title = '修改用户'
        if (this.roleCode) {
          this.roleId = scope.role
          this.roleIdCopy = scope.roleId
        } else {
          this.roleList.forEach(element => {
            if (scope.roleId === element.id) {
              this.roleId = element.id
            }
          })
        }
      }
      this.userVisible = true
    },
    // 获取角色下拉
    async getRoleList() {
      await this.$https({
        method: 'get',
        url: '/api/roleList',
        data: {}
      })
        .then(res => {
          if (res.code === 0) {
            this.roleList = res.data
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    getPagChange(data) {
      this.page = data.currentPage
      this.size = data.pagesize
      this.getData()
    },
    handleClick(val, scope) {
      this.userId = scope.id
      if (val === '编辑') {
        this.addUser('修改', scope)
        this.roleCode = false
        // 用户如果为这四个角色中的一个，则不可以更改该用户角色属性
        if (
          scope.roleCode == 'admin' ||
          scope.roleCode == 'pAdmin' ||
          scope.roleCode == 'mAdmin' ||
          scope.roleCode == 'youke'
        ) {
          this.roleCode = true
        }
        this.userName = scope.userName
        this.userPhone = scope.phone
        this.userAccount = scope.loginName
      } else if (val === '重置密码') {
        this.resetPassWord()
      } else if (val === '停用') {
        this.$confirm('是否停用该用户', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.stopUser()
          })
          .catch(() => {
            this.$message('已取消')
          })
      } else if (val === '启用') {
        this.$confirm('是否启用该用户', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.stopUser()
          })
          .catch(() => {
            this.$message('已取消')
          })
      } else {
        this.delUser()
      }
    },
    // 删除用户
    delUser() {
      this.$confirm('是否删除该用户', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$https({
            method: 'post',
            url: '/User/deleteUser',
            data: {
              userId: this.userId
            }
          })
            .then(res => {
              if (res.code === 0) {
                this.page = 1
                this.$message.success('删除成功')
                this.getData()
              } else {
                this.$message.error(res.msg)
              }
            })
            .catch(err => {
              console.log(err)
            })
        })
        .catch(() => {
          this.$message('已取消')
        })
    },
    // 停用用户
    stopUser() {
      this.$https({
        method: 'post',
        url: '/User/stopUser',
        data: {
          userId: this.userId
        }
      })
        .then(res => {
          if (res.code === 0) {
            this.getData()
            this.$message.success('操作成功')
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    //  重置用户密码
    resetPassWord() {
      this.$confirm('是否重置该用户的密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$https({
            method: 'post',
            url: '/User/resetPassword',
            data: {
              userId: this.userId
            }
          })
            .then(res => {
              if (res.code === 0) {
                this.$message.success('重置成功')
                this.getData()
              } else {
                this.$message.error(res.msg)
              }
            })
            .catch(err => {
              console.log(err)
            })
        })
        .catch(() => {
          this.$message('已取消')
        })
    },
    closeDialog(done) {
      this.title = ''
      this.roleId = null
      this.userId = null
      this.roleList = []
      this.userName = ''
      this.userPhone = ''
      this.userAccount = ''
      done()
    },
    close() {
      this.title = ''
      this.roleId = null
      this.userId = null
      this.roleList = []
      this.userName = ''
      this.userPhone = ''
      this.userAccount = ''
      this.userVisible = false
    },
    getData() {
      this.$https({
        method: 'post',
        url: '/User/listEnterpriseUser',
        data: {
          page: this.page,
          size: this.size
        }
      })
        .then(res => {
          if (res.code === 0) {
            this.tableData = res.data.records
            this.total = res.data.total
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    sortChange() {},
    addIndex(index) {
      return index + 1 + (this.page - 1) * this.size
    },
    tabRowClassName({ row, rowIndex }) {
      let index = rowIndex + 1
      if (index % 2 == 0) {
        return 'warning-row'
      }
    }
  }
}
</script>
<style lang="less" scoped>
#user-wrap {
  height: 100%;
  .add-user {
    display: flex;
    justify-content: flex-end;
    padding: 16px;
  }
  .xz {
    width: 60px;
  }
  .xg {
    color: #166df1;
  }
  .sc,
  .ty {
    color: #ff3d3d;
  }
  .add {
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    width: 114px;
  }
  .list-container {
    height: calc(100% - 104px);
    padding: 0px 16px 40px 16px;
    .tables {
      height: calc(100% - 62px);
    }
  }
}
</style>
<style lang="less">
#user-wrap {
  .user-dialog {
    .el-select {
      width: 100%;
    }
    .el-input__inner {
      width: 280px;
    }
    .select {
      .el-input__inner {
        width: 150px;
      }
    }
  }
}
</style>
